package diamond.day01;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionTest {
    @Test
    public void test1(){
        // 1、创建Person类对象
        Person p1 = new Person("tom",12);
        // 2、调用对象的属性
        p1.setAge(10);
        // 3、调用方法
        System.out.println(p1.toString());
    }

    @Test
    public void test2() throws Exception{
        // 1、通过反射创建Person类
        Class clazz = Person.class;
        Constructor constructor = clazz.getConstructor(String.class, int.class);
        Object tom = constructor.newInstance("Tom", 12);
        Person p = (Person)tom;
        System.out.println(p.toString());
        // 2、通过反射，调用对象指定属性、方法
        // 调用属性
        Field age = clazz.getDeclaredField("age");
        age.set(p,10);
        System.out.println(p.toString());
        // 调用方法
        Method show = clazz.getDeclaredMethod("show");
        show.setAccessible(true);
        show.invoke(p);

        Method getAge = clazz.getDeclaredMethod("getAge");
        getAge.setAccessible(true);
        Object age1 = getAge.invoke(p);
        System.out.println(age1);

        Method setAge = clazz.getMethod("setAge",int.class);
        setAge.setAccessible(true);
        setAge.invoke(p, 20);
        System.out.println(p.toString());
    }
    // 什么时候使用反射：反射的特性“动态性”
}
